package com.jqsoft.launcher.activity.task;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.activity.bean.WorkpersonBean;
import com.jqsoft.launcher.activity.diabetesMellitus.DiabetesMellitusFollowUpActivity2;
import com.jqsoft.launcher.activity.highblood.HBPFollowUpRecordActivity2;
import com.jqsoft.launcher.activity.majorPsychosis.MajorPsychosisFollowUpActivity2;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class TaskdetailActivity extends JQActivity implements OnClickListener {
	private List<WorkpersonBean> infoList = new ArrayList<WorkpersonBean>();
	private String dataType, pageNo, ID, title, allcount, IDs;
	private Button totalcount_bt;

	private ListView listview;// 列表
	private ListAdapter adapter;

	// 请求的结果
	private String sResult;
	private String sMessage;

	private View moreView;
	private LinearLayout progressBar_ll; // 更多等待层
	private Button moreButton;
	private int jiciNum = 0;// 第几次点击加载更多

	private int alltiao = 0;// 总共多少条
	private int jiazaitiao = 0;// jiazai多少条
	private int startIndex = 1, endIndex = 10;

	private WorkpersonBean xuanzhong_tiao;
	private CheckBox xzCheckbox, current_xzCheckbox;
	private Button quick_suifang_bt;

	@Override
	protected int getContentLayout() {
		return R.layout.taskdetail_layout;
	}

	@Override
	protected void initGui() {
		listview = (ListView) findViewById(R.id.task_detail_lv);
		totalcount_bt = (Button) findViewById(R.id.totalcount_bt);
		quick_suifang_bt = (Button) findViewById(R.id.quick_suifang_bt);
		quick_suifang_bt.setOnClickListener(this);

		moreView = getLayoutInflater().inflate(
				R.layout.finance_fund_pagination_more, null);
		moreButton = (Button) moreView.findViewById(R.id.loadMore);
		moreButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				moreButton.setVisibility(View.GONE);
				progressBar_ll.setVisibility(View.VISIBLE);
				jiciNum++;
				startIndex = jiciNum * 10 + 1;
				endIndex = jiciNum * 10 + 10;
//				if (endIndex > alltiao) {
//					endIndex = alltiao;
//				}
//				IDs = CommonUtil.getIndexStr(ID.split(","), startIndex,
//						endIndex);
				requstMethod();

			}
		});
		progressBar_ll = (LinearLayout) moreView
				.findViewById(R.id.progressBar_ll);
	}

	@Override
	protected void initAction() {
		setGoBack();
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				WorkpersonBean obj = (WorkpersonBean) listview
						.getItemAtPosition(position);
				xuanzhong_tiao = obj;
				xzCheckbox = (CheckBox) view.findViewById(R.id.xuanzhong_cb);
				for (int i = 0; i < infoList.size(); i++) {
					infoList.get(i).setCheck(false);
				}
				obj.setCheck(true);
				if (current_xzCheckbox != null) {
					current_xzCheckbox.setChecked(false);
				}
				xzCheckbox.setChecked(true);
				current_xzCheckbox = xzCheckbox;
				adapter.notifyDataSetChanged();
			}

		});
	}

	@Override
	protected void initData() {
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			dataType = bundle.getString("dataType");
			pageNo = bundle.getString("pageNo");
		//	ID = bundle.getString("ID");
			allcount = bundle.getString("allcount");
			title = bundle.getString("title");
		}

		setTitle(title);
		requstMethod();
//		alltiao = ID.split(",").length;
//		if (alltiao <= 10) {
//			IDs = ID;
//		} else {
//			IDs = CommonUtil.getIndexStr(ID.split(","), startIndex, endIndex);
//		}
//		if (StringTools.isNotEmpty(IDs)) {
//			requstMethod();
//		} else {
//			MessageTools.showDialogOk(ctx, "近期没有随访提醒！");
//		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.quick_suifang_bt:// 随访按钮
			if (current_xzCheckbox == null && infoList.size() > 1) {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
				return;
			}
			if ("1".equals(pageNo)) {
				Intent intent = new Intent(act,HBPFollowUpRecordActivity2.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("WorkpersonBean", xuanzhong_tiao);//HBPGuanLi_PersonInfo
				intent.putExtras(bundle);
				startActivity(intent);
			} else if ("2".equals(pageNo)) {
				Intent intent = new Intent(act,DiabetesMellitusFollowUpActivity2.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("WorkpersonBean", xuanzhong_tiao);
				intent.putExtras(bundle);
				startActivity(intent);
			} else if ("3".equals(pageNo)) {
				Intent intent = new Intent(act,MajorPsychosisFollowUpActivity2.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("WorkpersonBean", xuanzhong_tiao);
				intent.putExtras(bundle);
				startActivity(intent);
			}
			return;
		}
	}

	private final Handler showDownLoadHandle = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MSG_LOAD_OVER:
				dismissrogressBar();
				if ("1".equals(sResult)) {
					if (jiciNum == 0) {
						adapter = new ListAdapter();

						if (alltiao > endIndex) {
							listview.addFooterView(moreView);
						}
						listview.setAdapter(adapter);
						totalcount_bt.setText("（已加载" + infoList.size() + "条/"
								+ "共计" + alltiao + "条）");
						dismissrogressBar();
					} else {
						totalcount_bt.setText("（已加载" + infoList.size() + "条/"
								+ "共计" + alltiao + "条）");
						if (infoList.size() >= alltiao) {
							listview.removeFooterView(moreView);
						} else {
							progressBar_ll.setVisibility(View.GONE);
							moreButton.setVisibility(View.VISIBLE);
						}
						adapter.notifyDataSetChanged();
					}
				} else {
					MessageTools.showDialogOk(ctx, sMessage);
				}
				break;
			case Constant.MSG_LOAD_ERROR:
				dismissrogressBar();
				MessageTools.showDialogOk(ctx, "请求失败！");
				break;
			case Constant.MSG_LOAD_ZARO:
				dismissrogressBar();
				MessageTools.showDialogOk(ctx, "近期没有随访提醒！");
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	public void requstMethod() {
		UserLoginInfo info = UserLoginInfo.getInstances();
		loadWaitPanel();
		final JSONObject requestdata = new JSONObject();
		try {
			if (jiciNum != 0) {
				requestdata.put("iCurrentPageIndex", jiciNum + "");//(jiciNum * 10 + 1)
			} else {
				requestdata.put("iCurrentPageIndex", "1");
			}
			requestdata.put("dataType", dataType);
			requestdata.put("pageNo", pageNo);
			requestdata.put("sLoginName", info.getsLoginName());
			requestdata.put("sInputDeptCode", info.getsOrganizationKey());
			requestdata.put("iPageSize", "10");

		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		new Thread() {
			public void run() {
				String serviceURL = BphsURL.getCommonPath("GongzuoRemind_URL");
				String methodName = BphsURL
						.getCommonPath("GongzuoDetailRemind_METHOD");
				// String methodName = "GetMingxi";
				// String serviceURL =
				// "http://192.168.44.163:9099/WebService/RemindWebService.asmx";
				String result = WebServiceUtils.requestByParams(methodName,
						requestdata.toString(), serviceURL);
				// {"sSuccess":"1","sMessage":"执行功能！","AllCount":2,"Data":"{\"Table\":[{\"sNo\":\"34120410320000095\",\"sPersonName\":\"李凤才\",\"sSexName\":\"男\",\"dCreateTime\":\"2010/12/13 0:00:00\",\"sCardNo\":\"341204193808181617\",\"dVisitingDate\":\"2014/8/29 0:00:00\",\"dNextVisitingDate\":\"2014/11/29 0:00:00\",\"sAddress\":\"\",\"sVisitingState\":\"已超时3天\",\"RowNumber\":\"1\",\"COUNTS\":\"2\"},{\"sNo\":\"34120410320000095\",\"sPersonName\":\"李凤才\",\"sSexName\":\"男\",\"dCreateTime\":\"2010/12/13 0:00:00\",\"sCardNo\":\"341204193808181617\",\"dVisitingDate\":\"2014/7/7 16:06:44\",\"dNextVisitingDate\":\"2014/10/7 0:00:00\",\"sAddress\":\"\",\"sVisitingState\":\"已超时56天\",\"RowNumber\":\"2\",\"COUNTS\":\"2\"}]}"}
				parseResultJson(result);
			}
		}.start();
	}

	private void parseResultJson(String result) {
		if (StringUtils.isNotBlank(result)) {

			JSONObject json;
			try {
				json = new JSONObject(result);
				sResult = json.getString("sSuccess");
				sMessage = json.getString("sMessage");
				String data = json.getString("Data");
				JSONArray jsonArray1 = new JSONArray(
						new JSONObject(data).getString("Table"));
				alltiao = jsonArray1.length();
				if ("0".equals(sResult)) {
					showDownLoadHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				} else {

					for (int i = 0; i < jsonArray1.length(); ++i) {
						JSONObject jsonData = (JSONObject) jsonArray1.get(i);
						WorkpersonBean bean = new WorkpersonBean(
								jsonData.getString("sPersonID"),
								jsonData.getString("sNo"),
								jsonData.getString("sPersonName"),
								jsonData.getString("sSexName"),
								jsonData.getString("dBirthday"),
								jsonData.getString("dCreateTime"),
								jsonData.getString("sCardNo"),
								jsonData.getString("dVisitingDate"),
								jsonData.getString("dNextVisitingDate"),
								jsonData.getString("sAddress"),
								jsonData.getString("sVisitingDoctor"));
						if (jsonArray1.length() == 1) {
							bean.setCheck(true);
							xuanzhong_tiao = bean;
						}
						infoList.add(bean);
					}
					showDownLoadHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				}
			} catch (JSONException e) {
				showDownLoadHandle.sendEmptyMessage(Constant.MSG_LOAD_ZARO);
				e.printStackTrace();
			}
		} else {
			showDownLoadHandle.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
		}
	};

	private class ListAdapter extends BaseAdapter {

		public int getCount() {
			return infoList.size();
		}

		public Object getItem(int position) {
			return infoList.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(act);

			convertView = inflater.inflate(R.layout.taskdetail_item, null);
			TextView dangan_num_tv = (TextView) convertView
					.findViewById(R.id.dangan_num_tv);
			TextView name_tv = (TextView) convertView
					.findViewById(R.id.name_tv);
			TextView sex_tv = (TextView) convertView.findViewById(R.id.sex_tv);
			TextView birthday_tv = (TextView) convertView
					.findViewById(R.id.birthday_tv);
			TextView shengfenzheng_tv = (TextView) convertView
					.findViewById(R.id.shengfenzheng_tv);
			TextView dNextVisitingDate_tv = (TextView) convertView
					.findViewById(R.id.dNextVisitingDate_tv);
			TextView sAddress_tv = (TextView) convertView
					.findViewById(R.id.sAddress_tv);
//			TextView sVisitingState_tv = (TextView) convertView
//					.findViewById(R.id.sVisitingState_tv);
			TextView sDoctorName_tv = (TextView) convertView
					.findViewById(R.id.sDoctorName_tv);

			CheckBox cb = (CheckBox) convertView
					.findViewById(R.id.xuanzhong_cb);

			dangan_num_tv.setText(infoList.get(position).getsNo());
			name_tv.setText(infoList.get(position).getsPersonName());
			sex_tv.setText(infoList.get(position).getsSexName());
			birthday_tv.setText(CommonUtil.calcAge2(infoList.get(position)
					.getdBirthday()) + "");
			shengfenzheng_tv.setText(infoList.get(position).getsCardNo());
			dNextVisitingDate_tv.setText(CommonUtil.String2date(infoList.get(
					position).getdNextVisitingDate()));
			sAddress_tv.setText(infoList.get(position).getsAddress());
//			sVisitingState_tv.setText(infoList.get(position)
//					.getsVisitingState());
			sDoctorName_tv.setText(infoList.get(position).getsDoctorName());

			cb.setChecked(infoList.get(position).isCheck());
			return convertView;
		}
	}

}
